<template>
  <div class="bg global_bg">
    <VantNavigationBar title="地址管理"></VantNavigationBar>
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <van-loading vertical>
        <template #icon>
          <van-icon name="star-o" size="30" />
        </template>
        加载中...
      </van-loading>
    </div>
    <div v-else>
      <div>
        <van-address-list
          v-model="chosenAddressId"
          :list="addressList"
          default-tag-text="默认"
          @add="onAdd"
        />
      </div>
      <div v-if="addressList.length === 0">
        <van-empty description="请添加地址！" />
      </div>
    </div>
  </div>
</template>

<script>
import { AddressList, showToast, Empty, Loading } from 'vant'
import VantNavigationBar from '@/components/Navbar'
import { ref } from 'vue'
import mine from '@/api/mine.js'
import { useRouter } from 'vue-router'
import routerURL from '@/router/routerURL.js'

export default {
  components: {
    VantNavigationBar,
    [AddressList.name]: AddressList,
    [showToast.name]: showToast,
    [Empty.name]: Empty,
    [Loading.name]: Loading,
  },
  setup() {
    const router = useRouter()
    const chosenAddressId = ref(null)
    const addressList = ref([])
    const loading = ref(true) // 加载状态

    const onAdd = () => {
      router.push({ path: routerURL.MY_EDIT_ADDRESS })
    }

    mine.AddressListApi().then((res) => {
      const transformedData = res.data.map((item) => ({
        id: item.address_id,
        name: item.addressee,
        tel: item.addressee_iphon,
        address: item.detailed_address,
        isDefault: item.is_default,
      }))

      addressList.value = transformedData

      // 找到默认地址的id
      const defaultAddressId = transformedData.find(
        (item) => item.isDefault
      )?.id
      chosenAddressId.value = defaultAddressId // 设置默认地址的id
      loading.value = false // 加载完成后隐藏加载状态
    })

    return {
      addressList,
      onAdd,
      chosenAddressId,
      loading,
    }
  },
}
</script>

<style></style>
